import axios from 'axios'
import {ElNotification} from 'element-plus'
import router from '@/router'

const baseUrlStr = ""

const request = axios.create({
    baseURL: baseUrlStr,
    withCredentials: true
})

// request 拦截器
request.interceptors.request.use(config => {
    return config
}, error => {
    return Promise.reject(error)
});

// response 拦截器
// 可以在接口响应后统一处理结果
request.interceptors.response.use(
    response => {
        // 判断是否是流下载
        const contentType = response.headers['content-type']
        if (contentType.startsWith("application/octet-stream") || contentType.startsWith("application/x-zip-compressed") ||
            contentType.startsWith("application/vnd.openxml")) {
            // 文件下载处理
            return doFileStream(response);
        } else {
            // 处理通用响应数据
            return doCommonJsonRes(response, contentType);
        }
    },
    error => {
        ElNotification({
            title: 'Error',
            message: error,
            type: 'error',
        })
        return Promise.reject(error)
    }
)

function doFileStream(response) {
    // 下载文件
    let filename = response.headers['content-disposition']?.split('filename=')[1]
    filename = decodeURIComponent(filename);
    if (filename.startsWith('"')) {
        filename = filename.substring(1, filename.length - 1)
    }
    if (filename.endsWith('"')) {
        filename = filename.substring(0, filename.length - 2)
    }
    // 创建一个 Blob 对象
    const url = window.URL.createObjectURL(new Blob([response.data]));
    // 创建一个 <a> 元素
    const link = document.createElement('a');
    link.href = url;
    // 设置下载文件名，可根据实际情况修改
    link.setAttribute('download', filename);
    document.body.appendChild(link);
    // 模拟点击下载链接
    link.click();
    // 移除下载链接
    document.body.removeChild(link);
    // 释放 URL 对象
    window.URL.revokeObjectURL(url);
    return {};
}

function doCommonJsonRes(response, contentType) {
    let res = response.data;
    if (!contentType.startsWith("application/json")) {
        if (typeof res !== "object") {
            res = JSON.parse(res);
        }
    }
    // 判断是否成功访问
    if (res.code === 200 || res.code === '200') {
        return res;
    }
    axios({
        method: "post",
        url: baseUrlStr + "/ywu/data/dict/data.dict.query.info",
        data:{
            name: "com.ywu.route.to.by.code"
        }
    }).then(dictRes => {
        let dataValueInfo = dictRes.data.data.value;
        let routeList = JSON.parse(dataValueInfo);
        for (let index = 0; index < routeList.length; index++) {
            let routeInfo = routeList[index];
            if (routeInfo.code === res.code) {
                // 重新路由至登录界面
                router.push({path: routeInfo.routeTo})
            }
        }
    })
    ElNotification({
        title: 'Error',
        message: res.errorCode + ":" + res.message,
        type: 'error',
    })
    return Promise.reject(res.errorCode)
}

export default request;